#include "timer4.h"



void Timer4_init()
{
  
  //Clock source for TIM4 and TIM4CH1 output as PWM
  
  //Timer 4 channel 1 == PD12, follows the configuration: 
  RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN;
  RCC->APB1ENR |= RCC_APB1ENR_TIM4EN;
  
  TIM4->PSC = 23; // Set prescaler to 24 (PSC + 1)
  TIM4->ARR = 4096; // Auto reload value 4096 (PWM resolution 12-bits)
  TIM4->CCR1 = 2000; // Start value channel 1

  TIM4->CCMR1 = TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1; // PWM mode on channel 1

  TIM4->CCER = TIM_CCER_CC1E; // Enable compare on channel 1
  TIM4->CR1 = TIM_CR1_CEN; // Enable timer
  
  GPIOD->MODER |= (2 << (12 * 2)); // PD12 as alternate function
  GPIOD->AFR[1] |= (2  << (4  * 4)); //PD12 alternate function set as TIM4CH1
  
}

void Timer4_PWM_set(int value)
{
  TIM4->CCR1 = value;
}